package com.ytt.myspringboot_project.o1kafka.consumer;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ytt.myspringboot_project.o1kafka.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class O1TemperatureConsumer {
    @Value("${kafka.topic.temperature}")
    private String topic;

    @Value("${rsa.privateKey}")
    private String privateKeyStr;

    @Value("${aes.key}")
    private String aesKey;
    @KafkaListener(topics = "${kafka.topic.temperature}")
    public void listen(ConsumerRecord<String, String> record, Acknowledgment ack) throws JsonProcessingException {
        RSA rsa = new RSA(privateKeyStr, null);
        AES aes = new AES(aesKey.getBytes());
        String userValue = record.value();
        // AES 解密
//        String decryptedUserJson = AesUtil.decrypt(userValue,aesKey);
        String decryptedUserJson = aes.decryptStr(userValue);



        // 反序列化 User 对象
        User user = new ObjectMapper().readValue(decryptedUserJson, User.class);
        log.info("解密后的用户是：{}",user);
        // RSA 解密 idCard
        String decryptedIdCard = null;
        try {
            decryptedIdCard = rsa.decryptStr(user.getIdCard(), KeyType.PrivateKey);
            log.info("解密后的身份证是：{}",decryptedIdCard);
        } catch (Exception e) {
            log.error("RSA解密失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
        user.setIdCard(decryptedIdCard);
        System.out.println("消费者收到消息: " + user);

        ack.acknowledge();
    }
}
